package com.xy.job.admin.core

import com.xy.job.admin.common.NODE_REFRESH_INTERVAL
import com.xy.job.admin.service.NodeRegistryService
import jakarta.annotation.PreDestroy
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler
import org.springframework.stereotype.Component
import java.util.concurrent.TimeUnit

@Component
class NodeRegisterExecutor(
    private var inetAddressHolder: InetAddressHolder,
    private var nodeRegistryService: NodeRegistryService,
    private var registerExecutor: ThreadPoolTaskScheduler,
){

    val log: Logger = LoggerFactory.getLogger(NodeRegisterExecutor::class.java)

    /**
     * 注册管理端调度节点
     */
    @Scheduled(fixedDelay = NODE_REFRESH_INTERVAL, timeUnit = TimeUnit.SECONDS, scheduler = "registerExecutor")
    fun registerAdminScheduleNode() {
        nodeRegistryService.registerAdminScheduleNode(inetAddressHolder.ip, inetAddressHolder.port)
    }

    /**
     * 注册管理端主节点
     */
    @Scheduled(fixedDelay = NODE_REFRESH_INTERVAL, timeUnit = TimeUnit.SECONDS, scheduler = "registerExecutor")
    fun registerAdminMasterNode() {
        if (!nodeRegistryService.isAdminMasterNode(inetAddressHolder.address)) {
            nodeRegistryService.registerAdminMasterNode(inetAddressHolder.ip, inetAddressHolder.port)
        }
    }

    /**
     * 清理下线节点
     */
    @Scheduled(fixedDelay = NODE_REFRESH_INTERVAL, timeUnit = TimeUnit.SECONDS, scheduler = "registerExecutor")
    fun cleanDeadNodeRegistry() {
        if (nodeRegistryService.isAdminMasterNode(inetAddressHolder.address)) {
            nodeRegistryService.cleanDeadNodeRegistry()
        }
    }

    /**
     * 刷新当前节点的过期时间
     */
    @Scheduled(fixedDelay = NODE_REFRESH_INTERVAL, timeUnit = TimeUnit.SECONDS, scheduler = "registerExecutor")
    fun nodeRegisterRefresh() {
        nodeRegistryService.refreshNodeRegistry(inetAddressHolder.address)
    }

    @PreDestroy
    fun removeSelfNodeRegistry() {
        registerExecutor.shutdown()
        log.info("注册线程池已经关闭")
        nodeRegistryService.removeNodeRegistry(inetAddressHolder.address)
        log.info("注册节点已移除")
    }
}